package org.bonorsoft.modules.control.util;

import lombok.SneakyThrows;
import org.apache.commons.io.output.ByteArrayOutputStream;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QrCodeUtils{
    /**
     * 绿色
     */
    private static final int GREEN = 0xFF00CD00;
    /**
     * 白色
     */
    private static final int WHITE = 0xFFFFFFFF;
    /**
     * 宽
     */
    private static final int WIDTH = 400;
    /**
     * 高
     */
    private static final int HEIGHT = 400;
    /**
     * 图片高度增加100
     */
    private static final int PIC_HEIGHT = HEIGHT + 60;

    /**
     * 二维码传图片
     *
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, PIC_HEIGHT, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < PIC_HEIGHT; y++) {
                image.setRGB(x, y, WHITE);
            }
        }
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? GREEN : WHITE);
            }
        }
        return image;
    }

    /**
     * 生成二维码
     *
     * @param content 扫描二维码的内容
     * @param format  图片格式 jpg
     *                文件
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static BufferedImage generateQrCode(String content, String format) throws Exception {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        @SuppressWarnings("rawtypes")
        Map hints = new HashMap();
        // 设置UTF-8， 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 1);
        // 设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 画二维码
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        return image;
    }

    /**
     * 把生成的图片写到本地磁盘
     *
     * @param qrcFile       路径
     * @param qrCodeContent 二维码内容
     * @param pressText     增加的文字
     * @throws Exception
     */
    public static void generateQrCode(File qrcFile, String qrCodeContent, String pressText) throws Exception {
        BufferedImage image = generateQrCode(qrCodeContent, "jpg");
        Graphics2D g = image.createGraphics();
         //读取Logo图片
        BufferedImage logo = ImageIO.read(new File("C:\\police\\upFiles\\qrcodeModel\\qrcode.png"));
        //设置logo的大小,本人设置为二维码图片的20%,因为过大会盖掉二维码
        int widthLogo = logo.getWidth(null) > image.getWidth() * 3 / 10 ? (image.getWidth() * 3 / 10) : logo.getWidth(null);
        int heightLogo = logo.getHeight(null) > image.getHeight() * 3 / 10 ? ((image.getHeight()-60) * 3 / 10) : logo.getWidth(null);
        //logo放在中心
        int x = (image.getWidth() - widthLogo) / 2;
        int y = ((image.getHeight() -60 ) - heightLogo) / 2;
        /*logo放在右下角
         *  int x = (image.getWidth() - widthLogo);
         *  int y = (image.getHeight() - heightLogo);*/
         //开始绘制图片
        g.drawImage(logo, x, y, widthLogo, heightLogo, null);
        //g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
        //g.setStroke(new BasicStroke(logoConfig.getBorder()));
        //g.setColor(logoConfig.getBorderColor());
        //g.drawRect(x, y, widthLogo, heightLogo);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //设置字体
        Font font = new Font("黑体", Font.PLAIN, 16);
        g.setFont(font);
        g.setColor(Color.black);
        FontMetrics metrics = g.getFontMetrics(font);
        // 文字在图片中的坐标 这里设置在中间
        int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
        int startY = HEIGHT + (PIC_HEIGHT - HEIGHT) / 2;
        g.drawString(pressText, startX, startY);

        g.dispose();
        image.flush();
        try {
            ImageIO.write(image, "jpg", qrcFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
